package scatter.captcha.rest.filter;

import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;
import scatter.captcha.rest.service.ICaptchaPreventService;
import scatter.captcha.rest.tools.RequestPurposeTools;
import scatter.common.ErrorCode;
import scatter.common.pojo.vo.ErrorVo;
import scatter.common.rest.tools.InterfaceTool;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>
 *
 * </p>
 *
 * @author yangwei
 * @since 2021-01-17 21:47
 */
@Slf4j
public class CaptchaPreventFilter extends OncePerRequestFilter implements InterfaceTool {

    @Autowired
    private ICaptchaPreventService iCaptchaPreventService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (!tryPreventWithoutValidateCaptcha(request,response)) {
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 尝试阻止尚未验证验证码的请求
     * @param request
     * @param response
     * @return
     */
    private boolean tryPreventWithoutValidateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String purpose = RequestPurposeTools.resolvePurpose(request);
        boolean shouldValidate = iCaptchaPreventService.isShouldValidate(purpose,request);
        if (shouldValidate) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            ErrorVo errorVo = ErrorVo.newErrorVo(ErrorCode.ERROR_SHOULD_CAPTCHA);
            out.write(toJsonStr(errorVo));
            out.flush();
            IoUtil.close(out);

            return true;
        }
        // 放过之后重置
        iCaptchaPreventService.reset(purpose,request);
        return false;
    }
}
